﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using IMS.Api.Repository;
using IMS.Api.Entity;
using Microsoft.Extensions.Configuration;
using IMS.Api.Utils;
using IMS.Api.ParamModel;
using Microsoft.AspNetCore.Authorization;

namespace IMS.Api.Controllers
{
    // 全局验证token
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class CommodityOrdersController : ControllerBase
    {
        // 定义调用订单表的接口
        private IRepository<CommodityOrders> _commodityOrdersRepository;
        // 定义调用用户表的接口
        private IRepository<Users> _usersRepository;
        // 定义调用订单类型表的接口
        private IRepository<CommodityTypes> _commodityTypesRepository;
        // 定义调用地址表的接口
        private IRepository<Addresses> _addressesTypesRepository;
        // 定义支付表的接口
        private IRepository<Payments> _paymentsTypesRepository;
        // 定义购物车表的接口
        private IRepository<ShoppingCarts> _shoppingCartsTypesRepository;
        // 定义token
        private TokenParameter _tokenParameter;
        // 定义配置访问接口
        private readonly IConfiguration _configuration;

        // 依赖注入
        public CommodityOrdersController(IConfiguration configuration, IRepository<CommodityOrders> commodityOrdersRepository, IRepository<Users> usersRepository, IRepository<CommodityTypes> commodityTypesRepository, IRepository<Payments> paymentsTypesRepository, IRepository<Addresses> addressesTypesRepository, IRepository<ShoppingCarts> shoppingCartsTypesRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _commodityOrdersRepository = commodityOrdersRepository;
            _commodityTypesRepository = commodityTypesRepository;
            _paymentsTypesRepository = paymentsTypesRepository;
            _addressesTypesRepository = addressesTypesRepository;
            _shoppingCartsTypesRepository = shoppingCartsTypesRepository;
            // Token
            _tokenParameter =
                configuration
                    .GetSection("tokenParameter")
                    .Get<TokenParameter>();
        }

        // 跳过token验证
        [AllowAnonymous]
        // 获取订单表数据
        [HttpGet]
        public dynamic GetCommodityOrdersList([FromQuery] Pager pager)
        {
            // 页码（当前第几页）
            var pageIndex = pager.PageIndex;
            // 页大小（一页里面行的数量）
            var pageSize = pager.PageSize;
            // 查询的内容
            var query = pager.Query;
            // 查询的类型
            var queryType = pager.QueryType;
            // 判断是否查询
            if (string.IsNullOrEmpty(query))
            {
                var commodityOrders = _commodityOrdersRepository.Table.ToList();
                // 判断订单表是否为空
                if (commodityOrders != null)
                {
                    // 订单表不为空
                    // 判断是否进入回收站
                    var recycle = pager.Recycle;
                    if (recycle)
                    {
                        // 进入回收站
                        // 查看状态为删除订单表
                        var deletedCommodity = _commodityOrdersRepository.DeleteTable;
                        // 给状态为删除的订单表分页
                        var deletedTable = deletedCommodity.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                        return JsonHelper.Serialize(new
                        {
                            Data = new { DeletedCommodityOrders = deletedTable, Pager = new { pageIndex, pageSize, PageTotal = deletedCommodity.Count() } },
                            Meta = new
                            {
                                Msg = "获取已删除订单列表成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 没有进入回收站
                        // 类型表
                        var commodityTypes = _commodityTypesRepository.Table.ToList();
                        // 订单表分页
                        var activedTable = commodityOrders.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                        return JsonHelper.Serialize(new
                        {
                            Data = new { CommodityOrders = activedTable, CommodityTypes = commodityTypes, Pager = new { pageIndex, pageSize, PageTotal = commodityOrders.Count() } },
                            Meta = new
                            {
                                Msg = "获取订单列表成功！",
                                Status = 200
                            }
                        });
                    }
                }
                else
                {
                    // 订单表为空
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = "订单列表获取异常！",
                            Status = 400
                        }
                    });
                }
            }
            else
            {
                // 判断查找类型（0--根据订单号查找，1--根据用户名称查找）
                if (queryType == 0)
                {
                    // 根据订单号查找
                    var commodityOrders = _commodityOrdersRepository.Table.Where(x => x.OrderNumber.Contains(query)).ToList();
                    // 判断查询的订单号查询是否为空
                    if (commodityOrders != null)
                    {
                        // 查询订单号数据不为空
                        // 给查询到的内容分页
                        var activedTable = commodityOrders.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        return JsonHelper.Serialize(new
                        {
                            Data = new { CommodityOrders = activedTable, Pager = new { pageIndex, pageSize, PageTotal = commodityOrders.Count() } },
                            Meta = new
                            {
                                Msg = "订单数据查询成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 查询的订单号数据为空
                        return JsonHelper.Serialize(new
                        {
                            Data = "",
                            Meta = new
                            {
                                Msg = "没有找到你查询的订单数据！",
                                Status = 400
                            }
                        });
                    }
                }
                else if (queryType == 1)
                {
                    // 根据用户名称查找用户Id
                    var userId = _usersRepository.Table.Where(x => x.Username.Contains(query)).ToList().FirstOrDefault().Id;
                    // 根据用户Id查找订单
                    var commodityOrders = _commodityOrdersRepository.Table.ToList().Where(x => x.FromUserId == userId);
                    // 判断查询的订单名称是否为空
                    if (commodityOrders != null)
                    {
                        // 查询的订单名称不为空
                        // 给查询到的内容分页
                        var activedTable = commodityOrders.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        return JsonHelper.Serialize(new
                        {
                            Data = new { CommodityOrders = activedTable, Pager = new { pageIndex, pageSize, PageTotal = commodityOrders.Count() } },
                            Meta = new
                            {
                                Msg = "订单数据查询成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 查询的订单名称为空
                        return JsonHelper.Serialize(new
                        {
                            Data = "",
                            Meta = new
                            {
                                Msg = "没有找到你查询的订单名称！",
                                Status = 400
                            }
                        });
                    }
                }
                else
                {
                    // 查询的类型有误
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = "你的查询请求类型有误！",
                            Status = 400
                        }
                    });
                }
            }
        }

        // 跳过token验证
        [AllowAnonymous]
        // 根据订单Id获取订单
        [HttpGet("id/{id}"), Route("id")]
        public dynamic GetCommodityById(int id)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // var categoryId = _commodityTypesRepository.Table.Where(x => x.Id == commodityOrders.CategoryId).ToList()[0].Id;
            // 判断传入的id是否在类型表存在
            if (commodityOrders != null)
            {
                // 查询的Id的订单表存在
                return JsonHelper.Serialize(new
                {
                    Data = new { CommodityOrders = commodityOrders },
                    Meta = new
                    {
                        Msg = "订单数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的订单表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "订单数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 跳过token验证
        [AllowAnonymous]
        // 根据用户Id获取订单
        [HttpGet("uid/{id}"), Route("id")]
        public dynamic GetCommodityByUid(int id)
        {
            var commodityOrders = _commodityOrdersRepository.Table.Where(x => x.FromUserId == id).ToList();
            // 判断传入的用户id是否在类型表存在
            if (commodityOrders != null)
            {
                // 查询的用户Id的订单表存在
                return JsonHelper.Serialize(new
                {
                    Data = new { CommodityOrders = commodityOrders },
                    Meta = new
                    {
                        Msg = "订单数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的用户Id的订单表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "订单数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 跳过token验证
        [AllowAnonymous]
        // 根据订单号获取订单
        [HttpGet("OrderNumber/{id}"), Route("id")]
        public dynamic GetCommodityByOrderNumber(string id)
        {
            var commodityOrders = _commodityOrdersRepository.Table.Where(x => x.OrderNumber.Contains(id)).ToList();
            // 判断传入的用户id是否在类型表存在
            if (commodityOrders != null)
            {
                // 查询的订单号的订单表存在
                return JsonHelper.Serialize(new
                {
                    Data = new { CommodityOrders = commodityOrders },
                    Meta = new
                    {
                        Msg = "订单数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的订单号的订单表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "订单数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 添加新订单
        [HttpPost]
        public dynamic AddCommodity(NewCommodityOrder model)
        {
            // 用户Id
            var fromUserId = model.FromUserId;
            // 用户名
            var userName = _usersRepository.Table.Where(x => x.Id == fromUserId).ToList().FirstOrDefault().Username;
            // 商品信息
            var commodityInfo = model.CommodityInfo;

            // // 商品地址Id
            // var deliveryAddressId = model.DeliveryAddressId;
            // // 商品地址
            // var deliveryAddress = _addressesTypesRepository.Table.Where(x => x.Id == model.DeliveryAddressId).ToList().FirstOrDefault().UserAddress;
            // // 商品收货人
            // var consignee = _addressesTypesRepository.Table.Where(x => x.Id == model.DeliveryAddressId).ToList().FirstOrDefault().Consignee;
            // // 收货人号码
            // var telephoneNumber = _addressesTypesRepository.Table.Where(x => x.Id == model.DeliveryAddressId).ToList().FirstOrDefault().TelephoneNumber;

            // 商品收货地址
            var deliveryAddress = _usersRepository.Table.ToList().Where(x => x.Id == fromUserId).FirstOrDefault().Address;
            // 商品收货人
            var consignee = _usersRepository.Table.ToList().Where(x => x.Id == fromUserId).FirstOrDefault().Nickname;
            // 收货人号码
            var telephoneNumber = _usersRepository.Table.ToList().Where(x => x.Id == fromUserId).FirstOrDefault().TelephoneNumber;
            // 支付金额
            var paymentAmount = model.PaymentAmount;
            // 支付方式
            var paymentId = model.PaymentId;
            // 支付名称
            var paymentName = model.PaymentId == 0 ? "未选择支付方式" : _paymentsTypesRepository.Table.Where(x => x.Id == paymentId).ToList().FirstOrDefault().PaymentType;
            // 订单号
            var orderNumber = model.OrderNumber;
            // 结算状态
            var settlementStatus = model.SettlementStatus ? model.SettlementStatus : false;
            // 发货状态
            var deliveryStatus = model.DeliveryStatus ? model.DeliveryStatus : false;

            // 判断商品信息和订单编号是否为空
            if (string.IsNullOrEmpty(commodityInfo) && string.IsNullOrEmpty(orderNumber))
            {
                // 订单标题和订单内容为空
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "插入的商品信息和订单编号不能为空，请确认后重试！",
                        Status = 400
                    }
                });
            }
            else
            {
                var commodityOrder = _commodityOrdersRepository.Table.ToList().Where(x => x.FromUserId == fromUserId && x.OrderNumber == orderNumber);
                if (commodityOrder.Count() > 0)
                {
                    return JsonHelper.Serialize(new
                    {
                        Data = commodityOrder,
                        Meta = new
                        {
                            Msg = "创建成功！",
                            Status = 200
                        }
                    });
                }
                else
                {
                    // 订单标题和订单内容不为空
                    var commodityOrders = new CommodityOrders
                    {
                        FromUserId = fromUserId,
                        UserName = userName,
                        // DeliveryAddressId = deliveryAddressId,
                        DeliveryAddress = deliveryAddress,
                        TelephoneNumber = telephoneNumber,
                        Consignee = consignee,
                        CommodityInfo = commodityInfo,
                        PaymentAmount = paymentAmount,
                        PaymentId = paymentId,
                        OrderNumber = orderNumber,
                        SettlementStatus = settlementStatus
                    };
                    // 插入订单
                    _commodityOrdersRepository.Insert(commodityOrders);

                    // 转化为商品Id数组
                    string[] commodities = commodityInfo.Split(",");
                    // 循环数组进行购物车商品删除
                    for (int i = 0; i < commodities.Length; i++)
                    {
                        // 转化为Id类型
                        var commodity = int.Parse(commodities[i]);
                        // 获取购物车要删除的Id
                        var shoppingCart = _shoppingCartsTypesRepository.Table.ToList().Where(x => x.FromUserId == fromUserId && x.CommodityId == commodity).FirstOrDefault();
                        if(shoppingCart != null){
                            var id = shoppingCart.Id;
                            
                        // 删除购物车的东西
                        _shoppingCartsTypesRepository.PseudoDeletion(id);
                        }
                    }

                    return JsonHelper.Serialize(new
                    {
                        Data = commodityOrders,
                        Meta = new
                        {
                            Msg = "创建成功！",
                            Status = 200
                        }
                    });
                }

            }
        }

        // 订单信息修改
        [HttpPut("{id}")]
        public dynamic ModCommodity(int id, NewCommodityOrder model)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // 判断所修改订单Id是否存在
            if (commodityOrders != null)
            {
                // 支付方式
                commodityOrders.PaymentId = model.PaymentId;
                // 支付名称
                commodityOrders.PaymentName = _paymentsTypesRepository.Table.Where(x => x.Id == model.PaymentId).ToList().FirstOrDefault().PaymentType;
                // 结算状态
                commodityOrders.SettlementStatus = model.SettlementStatus ? model.SettlementStatus : false;
                // 发货状态
                commodityOrders.DeliveryStatus = model.DeliveryStatus ? model.DeliveryStatus : false;

                // 更新订单
                _commodityOrdersRepository.Update(commodityOrders);

                return JsonHelper.Serialize(new
                {
                    Data = commodityOrders,
                    Meta = new
                    {
                        Msg = string.Format("你修改的订单的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 要修改的订单Id不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的订单不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 订单状态可用信息修改
        [HttpPut("status/{id}"), Route("status")]
        public dynamic ModStatus(int id)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // 判断对应Id的订单是否存在
            if (commodityOrders != null)
            {
                // 指定Id的订单存在
                _commodityOrdersRepository.ActiveStatus(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodityOrders,
                    Meta = new
                    {
                        Msg = string.Format("你修改的状态对应订单的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的订单不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的订单不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 订单信息删除（伪删除）
        [HttpDelete("{id}")]
        public dynamic DeleteCommodity(int id)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // 判断对应Id的订单是否存在
            if (commodityOrders != null)
            {
                // 对应Id的订单存在
                // 伪删除操作
                _commodityOrdersRepository.PseudoDeletion(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodityOrders,
                    Meta = new
                    {
                        Msg = string.Format("你删除的订单Id为 {0} 的数据,删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 对应Id的订单不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的订单Id为 {0} 的数据,执行删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 订单信息删除（彻底删除）
        [HttpDelete("delete/{id}"), Route("delete")]
        public dynamic CompletelyDeleteCommodity(int id)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // 判断对应Id的订单是否存在
            if (commodityOrders != null)
            {
                // 指定Id的订单存在
                // 彻底删除
                _commodityOrdersRepository.Delete(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodityOrders,
                    Meta = new
                    {
                        Msg = string.Format("你删除的Id为 {0} 的数据,彻底删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的类型不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的Id为 {0} 的数据,无法执行彻底删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 恢复被删除的订单数据
        [HttpDelete("recovery/{id}"), Route("recovery")]
        public dynamic RecoveryCommodity(int id)
        {
            var commodityOrders = _commodityOrdersRepository.GetById(id);
            // 判断对应Id的订单是否存在
            if (commodityOrders != null)
            {
                // 指定Id的订单存在
                // 恢复数据
                _commodityOrdersRepository.Recovery(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodityOrders,
                    Meta = new
                    {
                        Msg = string.Format("你恢复的订单的id为: {0} ，已经恢复成功，请注意查收！", id),
                        Status = 200
                    }

                });
            }
            else
            {
                // 指定Id的订单不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的订单不存在，恢复错误，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }
    }
}
